<template>
  <div class="padding-15">
    <el-row v-if="isCanBack" class="go-back">
      <el-col>
        <el-button
          class="fr"
          size="mini"
          type="success"
          @click="$router.go(-1)"
        >{{$t('back_to_previous_page')}}</el-button
        >
      </el-col>
    </el-row>

    <h3>{{$t('operation_history')}}</h3>
    <el-row>
      <el-col class="p-t-15">
        <el-table
          v-loading="listLoading"
          :data="listData"
          border
          fit
          highlight-current-row
        >
          <el-table-column
            type="index"
            width="120"
            :label="$t('serial_number')"
          />
          <el-table-column  :label="$t('time')" prop="createTime" align="center"/>
          <el-table-column  :label="$t('operated_by')" prop="sysUserName" align="center"/>
          <el-table-column  :label="$t('event')" prop="" align="center">
            <template slot-scope="{ row }">
              <span>{{ eventMap[row.operEvent] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <h3 class="data-record">
      <span>{{$t('data_logging')}}</span>
      <p>
        <el-date-picker
          v-model="datePicker"
          size="small"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="~"
          :start-placeholder="$t('start_date')"
          :end-placeholder="$t('end_date')"/>
        <el-button type="primary" size="small" class="m-r-20" @click="search">
          {{$t('search')}}
        </el-button>
        <span
          class="m-r-20"
        >{{$t('cumulative_time_on_the_shelf')}}： {{ totalObj.totalPromotionTime }}
        </span>
        <span class="m-r-20">{{$t('exposure')}}： {{ totalObj.totalShowCount }} </span>
        <span class="m-r-20"> {{$t('clicks')}}： {{ totalObj.totalClickCount }}</span>
        <el-button
          :disabled="echartObj.date && echartObj.date.length==0"
          size="small"
          type="primary"
          @click="toExport"
        >{{$t('export_doc')}}</el-button
        >
      </p>
    </h3>
    <div
      id="one"
      :style="{ width: '100%', height: '480px' }"
      class="p-t-15"
    />
    <el-dialog
      :title="$t('adjustment_display_data')"
      :visible.sync="showFakeAdjustmentModal"
      :close-on-click-modal="false"
      :show-close="false"
      width="650px"
      top="50px"
    >
      <div class="fake_adjustment_row">
        {{ $t('adjustment_to_times_of_real_data') }}
        <el-select v-model="fakeAdjustmentTimes_">
          <el-option
            v-for="times in 100"
            :key="times"
            :value="times"
            :label="times"
          />
        </el-select>
        {{ $t('multiples') }}
      </div>
      <div class="fake_adjustment_button">
        <el-button @click.stop="cancelFakeAdjustmentTimes">
          {{ $t('cancel') }}
        </el-button>
        <el-button type="primary" @click.stop="confirmFakeAdjustmentTimes">
          {{ $t('confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdDetailApi } from '@/api/advertisement/advertisementClick.js';
import echarts from 'echarts';
import timeUtils from '@/utils/timeHandle.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';

const tableHead = [
  {
    prop: 'date',
    label: 'date'
  },
  {
    prop: 'showCount',
    label: 'exposure'
  },
  {
    prop: 'clickCount',
    label: 'clicks'
  }
];

export default {
  name: 'AdDetail',
  data() {
    return {
      tableHead,
      datePicker: [],
      isCanBack: true,
      listLoading: false,
      btnLoading: false,
      statisticsData: {},
      listQuery: {
        adId: null,
        adType: null,
        startTime: '',
        endTime: ''
      },
      eventMap: {
        1: this.$t('created_this_ad'),
        2: this.$t('edited_the_ad'),
        3: this.$t('added_this_ad'),
        4: this.$t('downgraded_the_ad'),
        5: this.$t('deleted_this_ad')
      },
      showFakeAdjustmentModal: false,
      fakeAdjustmentTimes_: 1,
      fakeAdjustmentTimes: 1
    };
  },

  computed: {
    listData() {
      return this.statisticsData.adOperateLogList || [];
    },

    dailyDataList() {
      const data = this.statisticsData.dailyDataList || [];
      const times = this.fakeAdjustmentTimes;
      return data.map(t => ({
        ...t,
        showCount: t.showCount * times,
        clickCount: t.clickCount * times
      }));
    },

    totalObj() {
      const timeKeys = (obj, keys, times) => ({
        ...obj,
        ...keys.reduce((o, k) => ({ ...o, [k]: (obj[k] || 0) * times }), {})
      });
      const keys = ['totalClickCount', 'totalShowCount'];
      return timeKeys(
        this.$pick(['totalPromotionTime', ...keys])(this.statisticsData),
        keys,
        this.fakeAdjustmentTimes
      );
    },

    echartObj() {
      const data = this.dailyDataList || [];
      const group = (list, keys) =>
        list.reduce(
          (o, t) =>
            keys.reduce((r, k) => ((r[k] = (r[k] || []).concat(t[k])), r), o),
          {}
        );
      const { showCount, clickCount, calDate } = group(data, [
        'showCount',
        'clickCount',
        'calDate'
      ]);
      const series = [
        { name: this.$t('exposure'), type: 'line', data: showCount },
        { name: this.$t('clicks'), type: 'line', data: clickCount }
      ];

      return {
        legend: [this.$t('exposure'), this.$t('clicks')],
        series,
        date: calDate
      };
    },

    exportData() {
      const data = this.dailyDataList || [];
      return data.map(
        this.$pick({
          showCount: 'showCount',
          clickCount: 'clickCount',
          date: 'calDate'
        })
      );
    }
  },

  watch: {
    echartObj() {
      this.upDateEchart();
    }
  },

  created() {
    const { adId, adType } = this.$route.query;
    this.listQuery.adId = adId;
    this.listQuery.adType = adType;
    this.getList();
  },

  mounted() {
    this.upDateEchart();
  },

  methods: {
    search() {
      const { datePicker, listQuery } = this;
      const startTime = (datePicker && datePicker[0]) || '';
      const endTime = (datePicker && datePicker[1]) || '';
      this.listQuery = { ...listQuery, startTime, endTime };
      this.getList();
    },

    async getList() {
      try {
        const { code, data } = await getAdDetailApi(this.listQuery);
        if (code == 200) {
          this.statisticsData = data;
        }
      } catch (e) {
        console.log(e);
      }
    },
    cancelFakeAdjustmentTimes() {
      this.showFakeAdjustmentModal = false;
    },
    confirmFakeAdjustmentTimes() {
      this.fakeAdjustmentTimes = this.fakeAdjustmentTimes_;
      this.showFakeAdjustmentModal = false;
    },

    upDateEchart() {
      const myChart = echarts.init(document.getElementById('one'));
      myChart.showLoading();

      myChart.on('click', ({ componentType, targetType }) => {
        if (componentType === 'yAxis' && targetType === 'axisName') {
          this.showFakeAdjustmentModal = true;
        }
      });

      const { legend, series, date } = this.echartObj;
      const option = {
        color: this.$store.state.app.eChartColor,
        title: {
          show: !date || date.length == 0,
          textStyle: {
            color: '#909399',
            fontSize: 14,
            fontWeight: 400
          },
          text: this.$t('no_data_available'),
          left: 'center',
          top: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: legend
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: date
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: `(${this.$t('times')})`,
            axisLabel: {
              formatter: '{value}'
            },
            silent: false,
            triggerEvent: true
          }
        ],
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 100
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: 100
          }
        ],
        series
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    toExport() {
      const { exportData } = this;
      const tableName = this.$t('ad_details');
      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = tableHead.map(item => this.$t(item.label));
      const tKey = tableHead.map(item => item.prop);
      const data = formatJson(tKey, exportData);
      const fileName = tableName + exprtTime;
      exportJsonToExcel(tHeader, data, fileName);
    }
  }
};
</script>

<style lang="scss" scoped>
.data-record {
  margin-top: 15px;
  height: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 32px;

  .m-r-20 {
    margin-right: 20px;
  }
}

.fake_adjustment {
  &_button {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
